package com.wanmait.schedule.shiro;

import com.wanmait.schedule.exception.TeacherTokenException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JWTFilter extends BasicHttpAuthenticationFilter {

    //如果返回ture，则不执行登录，不检查token，如果返回false，则执行登录
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest req = (HttpServletRequest) request;
        //预检请求
        if("OPTIONS".equals(req.getMethod())){
            return true;
        }
        return false;
    }

    //是否要打算登录 可以检测请求头中是否包含token判断是否打算登录
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //获得token
        String token = req.getHeader("TeacherToken");
        if(token==null){
            //直接抛出异常不走统一的异常处理
            request.setAttribute("exception",new TeacherTokenException("管理员没有携带token"));
            request.getServletContext().getRequestDispatcher("/errorToken").forward(request, response);
            return false;
        }
        //主体提交认证
        try {
            BearerToken bearerToken = new BearerToken(token);
            this.getSubject(request, response).login(bearerToken);
        } catch (AuthenticationException e) {
            request.setAttribute("exception",e);
            request.getServletContext().getRequestDispatcher("/errorToken").forward(request, response);
            return false;
        }

        return true;
    }
}
